<template>
  <view class="flex-y-c container">
    <view class="login-type" :style="{ top: headerHeight + 10 + 'px' }" @click="loginType">
      <v--text v-if="loginMethod === 2">{{ loginPwd ? '验证码登录' : '密码登录' }}</v--text>
    </view>
    <image class="icon" src="@/static/logo.jpg"></image>
    <view class="company-name">福建省博士创新站</view>
    <view class="login-one" v-if="loginMethod === 1">
      <view class="login-btn">
        <u-button type="primary" shape="square" size="large" @click="handleWxLogin"
          >手机号快捷登录</u-button
        >
      </view>
      <view class="login-btn">
        <u-button shape="square" size="large" @click="switchLogin">其他账号登录</u-button>
      </view>
      <u-button shape="square" size="large" @click="goBack">暂不登录</u-button>
    </view>
    <view class="input-view" v-else>
      <block v-if="!loginPwd">
        <div class="input-inner">
          <u-input
            placeholder="请输入手机号码"
            border="bottom"
            type="number"
            maxlength="11"
            v-model="mobile"
            @change="changeInput"
          >
            <view slot="suffix">
              <u-code
                ref="uCode"
                @change="codeChange"
                seconds="60"
                changeText="X秒重新获取"
              ></u-code>
              <u--text @tap="getCode" :text="tips" type="info" size="mini"></u--text>
            </view>
          </u-input>
        </div>
        <div class="input-inner">
          <u--input
            placeholder="请输入验证码"
            border="bottom"
            type="number"
            maxlength="6"
            v-model="msgCode"
            @change="changeInput"
          >
          </u--input>
        </div>
      </block>
      <block v-else>
        <div class="input-inner">
          <u--input
            placeholder="请输入账号"
            border="bottom"
            v-model="account"
            @change="changeInput"
          >
          </u--input>
        </div>
        <div class="input-inner">
          <u--input
            placeholder="请输入密码"
            border="bottom"
            type="password"
            v-model="password"
            @change="changeInput"
          >
          </u--input>
        </div>
      </block>

      <u-button
        type="primary"
        :disabled="disabled"
        text="登录"
        class="login-btn"
        @click="confirmLogin"
      ></u-button>
      <view class="phone-login" @click="handleWxLogin">手机号快捷登录</view>
      <view class="phone-login" @click="goBack">暂不登录</view>
    </view>
    <public-confirm
      ref="confirm"
      message="是否获取手机号快速登录"
      :confShow="confShow"
      openType="getPhoneNumber"
      @confirm="weixinPhoneLogin"
      @cancel="cancel"
    ></public-confirm>
  </view>
</template>

<script>
import { reLaunch } from '@/ext/routeUtils'
import { encrypt } from '@/ext/aes'

export default {
  data() {
    return {
      confShow: false,
      loginMethod: 1,
      loginPwd: false,
      tips: '',
      mobile: '',
      msgCode: '',
      account: '',
      password: '',
      disabled: true,
      headerHeight: this.$globalData.state.headerHeight,
      openId: '',
      navUrl: '',
    }
  },
  onShow() {
    // if (this.$globalDate.state.token) {
    // 	uni.reLaunch({
    // 		url: '/index/index'
    // 	})
    // }
  },
  onLoad(param) {
    if (param.realNavUrl) this.navUrl = decodeURIComponent(param.realNavUrl)
    console.log('来的啥', this.navUrl)
  },
  watch: {},
  methods: {
    changeInput() {
      if (this.loginMethod === 2 && !this.loginPwd) {
        let isMobile = this.$utils.isPhoneNumber(this.mobile)
        if (isMobile && this.msgCode.length === 6) {
          this.disabled = false
        } else {
          this.disabled = true
        }
      } else {
        if (this.account.length > 0 && this.password.length > 0) {
          this.disabled = false
        } else {
          this.disabled = true
        }
      }
    },
    codeChange(text) {
      this.tips = text
    },
    getCode() {
      if (this.$refs.uCode.canGetCode) {
        // 向后端请求验证码
        this.$request('/user/sms', {
          mobile: this.mobile,
        }).then((res) => {
          uni.$u.toast('验证码已发送')
          this.$refs.uCode.start()
        })
      } else {
        uni.$u.toast('倒计时结束后再发送')
      }
    },
    confirmLogin() {
      if (this.loginMethod === 2 && !this.loginPwd) {
        this.$request('/user/loginBySms', {
          mobile: this.mobile,
          msgCode: this.msgCode,
        }).then((res) => {
          uni.$u.toast('登录成功')
          let token = res.result.tokenHead + res.result.token
          this.$globalData.commit('setLoginInfo', {
            token,
            userInfoDetail: {},
          })
          this.getUserInfo()
          // 连接获取聊天列表、socket
          // this.getListAndSocket()
          this.navBeforePage()
        })
      } else if (this.loginMethod === 2 && this.loginPwd) {
        this.$request('/user/loginByPassword', {
          account: this.account,
          password: encrypt(this.password),
        }).then((res) => {
          uni.$u.toast('登录成功')
          let token = res.result.tokenHead + res.result.token
          this.$globalData.commit('setLoginInfo', {
            token,
            userInfoDetail: {},
          })
          this.getUserInfo()
          // 连接获取聊天列表、socket
          // this.getListAndSocket()
          this.navBeforePage()
        })
      }
    },
    navBeforePage() {
      const beforeUrl = this.navUrl || '/pages/index/index'
      console.log('什么东西', beforeUrl)
      if (['/pages/index/index', '/pages/user/index', '/pages/new/mail'].includes(beforeUrl)) {
        this.$routeUtils.reLaunch({
          url: beforeUrl,
        })
      } else {
        this.$routeUtils.redirectTo({
          url: beforeUrl,
        })
      }
    },
    switchLogin() {
      this.loginMethod = 2
    },
    goBack() {
      uni.navigateBack()
    },
    loginType() {
      this.loginPwd = !this.loginPwd
    },
    handleWxLogin() {
      wx.login({
        success: (res) => {
          const code = res.code
          this.$request(`/user/wxLogin`, {
            code: code,
          }).then(
            (res) => {
              if (res.code === 21003) {
                this.confShow = true
                this.openId = res.result.openId
              } else {
                let token = res.result.tokenHead + res.result.token
                this.$globalData.commit('setLoginInfo', {
                  token,
                  userInfoDetail: {},
                })
                this.getUserInfo()
                // 连接获取聊天列表、socket
                // this.getListAndSocket()
                this.$routeUtils.reLaunch({
                  url: '/pages/index/index',
                })
              }
            },
            (err) => {
              console.log('失败', err)
            },
          )
        },
      })
    },
    weixinPhoneLogin(e) {
      this.confShow = false
      this.$request(`/user/wxBind`, {
        openId: this.openId,
        code: e.detail.code,
      }).then((res) => {
        let token = res.result.tokenHead + res.result.token
        this.$globalData.commit('setLoginInfo', {
          token,
          userInfoDetail: {},
        })
        this.getUserInfo()
        // 连接获取聊天列表、socket
        // this.getListAndSocket()
        this.$routeUtils.reLaunch({
          url: '/pages/index/index',
        })
      })
    },
    cancel() {
      this.confShow = false
    },
    // 获取登录用户信息
    getUserInfo() {
      this.$request(`/user/loginUser`, {}).then((res) => {
        let info = res.result
        this.$globalData.commit('setLoginInfo', {
          userInfoDetail: {
            userId: info.id,
            mobile: info.mobile,
            account: info.account, //管理员、部门账号
            identifying: info.identifying, //身份类型：管理员-admin，部门-dept，专家-professional，企业-enterprise，经理人-manager
            professionalApplyVo: info.professionalApplyVo, //专家信息
            enterpriseApplyVo: info.enterpriseApplyVo, //企业信息
            managerApplyVo: info.managerApplyVo, //经理人信息
          },
        })
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  background-image: url('https://honghai-res.oss-cn-hangzhou.aliyuncs.com/1648376052935.png');
  background-repeat: no-repeat;
  background-size: 100%;
  background-position: bottom;
  .login-type {
    position: absolute;
    top: 30rpx;
    right: 30rpx;
  }
}
.icon {
  width: 200rpx;
  height: 200rpx;
  border-radius: 36rpx;
  box-shadow: 0 2rpx 12rpx rgba(223, 228, 235, 0.3);
  margin-top: 180rpx;
}
.company-name {
  margin-top: 30rpx;
  font-weight: 400;
  font-size: 40rpx;
}
.login-one {
  width: 660rpx;
  margin-top: 160rpx;
  .login-btn {
    margin-bottom: 32rpx;
  }
}
.input-view {
  margin-top: 80rpx;
  .login-icon {
    width: 40rpx;
    height: 40rpx;
    margin-right: 20rpx;
  }
  .input-inner {
    height: 72rpx;
    width: 660rpx;
    // border-bottom: 2rpx solid #dfe4eb;
    display: flex;
    align-items: center;
    position: relative;
    margin-bottom: 28rpx;
    .line-input {
      font-size: 32rpx;
    }
    .short {
      width: 300rpx;
    }
  }
  .login-btn {
    margin-top: 68rpx;
  }
}
.phone-login {
  color: $uni-color-primary;
  margin-top: 40rpx;
  text-align: center;
}
</style>
